/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * https://www.renren.io
 *
 * 版权所有，侵权必究！
 */

package com.sew.sewweb.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sew.sewweb.common.config.BaseConfig;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 *
 * 调用u8c接口工具类
 */
public class CallU8CUtils {
	private static final Logger log = LoggerFactory.getLogger(CallU8CUtils.class);

	public static String operator(String url, Map<String, Object> headparams, String json) {
		HttpClient httpClient = new HttpClient();
		PostMethod httpPost = new PostMethod(url);
		httpPost.setRequestHeader("content-type",
				"application/json;charset=utf-8");
		for (Map.Entry<String, Object> entry : headparams.entrySet()) {
			httpPost.setRequestHeader(entry.getKey(), entry.getValue()
					.toString());
		}
		try {
			RequestEntity entity = new StringRequestEntity(json,
					"application/json", "UTF-8");
			httpPost.setRequestEntity(entity);
			httpClient.executeMethod(httpPost);
//			if (httpPost.getStatusCode() == HttpStatus.SUCCESS) {
//				// 通过读流的方式替代getResponseBodyAsString()
//				InputStream inputStream = httpPost.getResponseBodyAsStream();
//				BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
//				StringBuffer stringBuffer = new StringBuffer();
//				String str;
//				while((str = br.readLine()) != null){
//					stringBuffer.append(str);
//				}
//				String response = new String(stringBuffer);
//				br.close();
//				// String response = new String(postMethod.getResponseBodyAsString());
//				return response;
//			} else {
//				return httpPost.getResponseBodyAsString();
//			}
			return httpPost.getResponseBodyAsString();

		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * Md5加密 返回byte[]
	 *
	 * @param s
	 * @return
	 */
	private static byte[] md5(String s) {
		MessageDigest algorithm;
		try {
			algorithm = MessageDigest.getInstance("MD5");
			algorithm.reset();
			algorithm.update(s.getBytes("UTF-8"));
			byte[] messageDigest = algorithm.digest();
			return messageDigest;
		} catch (Exception e) {
			log.error("MD5 Error...", e);
		}
		return null;
	}
	/**
	 * byte[]解密 返回string
	 *
	 * @param hash
	 * @return
	 */
	private static final String toHex(byte hash[]) {
		if (hash == null) {
			return null;
		}
		StringBuffer buf = new StringBuffer(hash.length * 2);
		int i;

		for (i = 0; i < hash.length; i++) {
			if ((hash[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString(hash[i] & 0xff, 16));
		}
		return buf.toString();
	}
	/**
	 * hash加密
	 *
	 * @param s
	 * @return
	 */
	public static String hash(String s) {
		try {
			return new String(toHex(md5(s)).getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8);
		} catch (Exception e) {
			log.error("not supported charset...{}", e);
			return s;
		}
	}

	public static Map<String, Object> herder(){
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("trtype", "code");
		map.put("system", BaseConfig.getConfig().getString("system"));
		map.put("usercode", BaseConfig.getConfig().getString("usercode"));
		map.put("password", BaseConfig.getConfig().getString("password"));
		return map;
	}

	public static <T> IPage<T> listToPage(List<T> list, Integer current, Integer size){
		IPage<T> iPage = new Page<>(current,size);
		iPage.setTotal(list.size());
		int startIndex = (int)((current - 1)*size);
		if(null == list || list.isEmpty() || startIndex > list.size()){
			iPage.setRecords(null);
		}
		else {
			int toIndex = (int)(current*size);
			iPage.setRecords(list.subList(startIndex,toIndex > list.size() ? list.size() : toIndex));
		}
		return iPage;
	}


	/**
	 * 获取oa中token
	 * @return 返回token
	 */
	public static String getOAToken(String url){
		org.apache.http.client.HttpClient client = HttpClientBuilder.create().build();
		HttpGet request = new HttpGet(url);
		request.setHeader("Accept", "application/json");
		String result=null;
		try {
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			result= EntityUtils.toString(entity,"utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		}
		JSONObject jsonObject = JSON.parseObject(result);
		String token = jsonObject.getString("id");
//		String token = result;
		log.info("oa返回的token=" + token);
		return token;
	}

}
